package com.three.box

import android.annotation.SuppressLint
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import androidx.core.text.isDigitsOnly
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.flyco.tablayout.listener.CustomTabEntity
import com.google.gson.Gson
import com.google.zxing.client.android.Intents
import com.google.zxing.integration.android.IntentIntegrator
import com.hjq.toast.Toaster
import com.tencent.mmkv.MMKV
import com.three.box.activity.LoginActivity
import com.three.box.base.BaseActivity
import com.three.box.config.Constant
import com.three.box.databinding.ActivityMainBinding
import com.three.box.entity.LoginResult
import com.three.box.entity.TabEntity
import com.three.box.fragment.InBoxFragment
import com.three.box.helper.LogUtils
import com.three.box.network.AppRepository
import com.three.box.network.NetworkUtil
import com.three.box.scan.ACaptureActivity

class MainActivity : BaseActivity() {

    companion object {
        private const val TAG = "MainActivity"
        private const val REQUEST_CODE = 100
        private const val SCAN_ACTION = "com.android.server.three.box" // 定义广播名

    }

    private lateinit var binding: ActivityMainBinding

//    private val titles = listOf("入箱", "出箱")
    private val titles = listOf("入箱")
    private val fragments = ArrayList<Fragment>()
    private val tabEntities = ArrayList<CustomTabEntity>()
    private val inBoxFragment = InBoxFragment.newInstance()
//    private val outBoxFragment = InBoxFragment.newInstance()
    private var currentBoxId = 0

    private var currentPrefix = ""

    private var isVisitor = false

    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityMainBinding.inflate(layoutInflater)
        setStatusBar()
        super.onCreate(savedInstanceState)

        val temp = MMKV.defaultMMKV().decodeString(Constant.LOGIN_RESULT, "{}")
        val loginResult = Gson().fromJson(temp, LoginResult::class.java)
        if (loginResult.userInfo?.role == 2) {
            isVisitor = true
        }
        initValues()

        boardCastSetting()
        AppRepository.instance.configInfo { _, _ ->
        }
        reloadOperateType()

        if (Constant.TEST) {
            binding.root.postDelayed({
                loadBoxInfo("101")
            }, 500)
        }
    }

    private fun reloadOperateType() {
        AppRepository.instance.reloadOperateType(1)
        AppRepository.instance.reloadOperateType(2)
    }

    override fun getLayoutView() = binding.root

    private fun scan() {
        val joinedByComma = java.lang.StringBuilder()
        for (format in IntentIntegrator.QR_CODE_TYPES) {
            if (joinedByComma.isNotEmpty()) {
                joinedByComma.append(',')
            }
            joinedByComma.append(format)
        }

        val intent = Intent(this, ACaptureActivity::class.java)
        intent.action = Intents.Scan.ACTION
        intent.putExtra(Intents.Scan.FORMATS, joinedByComma.toString())

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
        startActivityForResult(intent, REQUEST_CODE)
    }

    private fun initValues() {
        binding.scanIv.setOnClickListener {
            scan()
        }
        binding.moreIv.setOnClickListener {
            MaterialDialog(this).show {
                val dialog = listItems(items = listOf("添加物品", "历史记录", "退出登录"), selection = { _, index, _ ->
                    if (index == 0) {
                        if (isVisitor) {
                            Toaster.show("游客无法使用此功能")
                            return@listItems
                        }
                        inBoxFragment.addProduct()
                    } else if (index == 1) {
                        if (isVisitor) {
                            Toaster.show("游客无法使用此功能")
                            return@listItems
                        }
                        inBoxFragment.addProductFromHistory(currentBoxId)
                    } else if (index == 2) {
                        MMKV.defaultMMKV().remove(Constant.TOKEN)
                        startActivity(Intent(this@MainActivity, LoginActivity::class.java))
                        finish()
                    }
                })
            }
        }
        fragments.add(inBoxFragment)

        for(index in titles.indices) {
            tabEntities.add(TabEntity(titles[index], 0, 0))
        }

        val adapter = BoxPagerAdapter(supportFragmentManager)
        binding.viewPager.adapter = adapter

        binding.tabLayout.setViewPager(binding.viewPager)
    }

    inner class BoxPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
        override fun getCount(): Int {
            return fragments.size
        }

        override fun getPageTitle(position: Int): CharSequence {
            return titles[position]
        }

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    override fun onResume() {
        // 注册广播接收器
        val intentFilter = IntentFilter(SCAN_ACTION)
        intentFilter.priority = Integer.MAX_VALUE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(scanReceiver, intentFilter, RECEIVER_EXPORTED)
        } else {
            registerReceiver(scanReceiver, intentFilter)
        }
        super.onResume()
    }

    private var scanReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == SCAN_ACTION) {
                val code = intent.getStringExtra("scannerdata")
                val boxId = parseResult(code)
                if (boxId.isEmpty()) {
                    Toaster.show("识别错误，请检查后重试")
                    return
                }

                loadBoxInfo(boxId)
            }
        }
    }

    private val boxPrefix1 = "铝合金收纳箱"
    private val boxPrefix2 = "防疫组装备"
    private fun parseResult(result: String?): String {
        if (result.isNullOrEmpty()) {
            return ""
        }
        if (result.startsWith(boxPrefix1)) {
            val boxId = result.removePrefix(boxPrefix1).removeSuffix("\n")
            if (!boxId.isDigitsOnly()) {
                return ""
            }
            currentPrefix = boxPrefix1
            return boxId
        } else if (result.startsWith(boxPrefix2)) {
            val boxId = result.removePrefix(boxPrefix2).removeSuffix("\n")
            if (!boxId.isDigitsOnly()) {
                return ""
            }
            currentPrefix = boxPrefix2
            return boxId
        }

        return ""
    }

    private fun loadBoxInfo(boxId: String) {
        if (!NetworkUtil.isNetworkAvailable(this)) {
            Toaster.show("网络错误，请检查后重试")
            return
        }
        AppRepository.instance.boxInfo(boxId) { code, box ->
            if (code != 0 || box == null) {
                Toaster.show("信息同步失败")
                return@boxInfo
            }
            Toaster.show("信息同步成功")
            binding.titleTv.text = "$currentPrefix：${box.boxId}"
            currentBoxId = box.id
            inBoxFragment.onBoxLoaded(box)
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        val result = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data)
        if (requestCode == REQUEST_CODE) {
            val index = REQUEST_CODE
            LogUtils.d(TAG, "result$index is $result")
            val boxId = parseResult(result.contents)
            if (boxId.isEmpty()) {
                Toaster.show("识别错误，请检查后重试")
                return
            }
            loadBoxInfo(boxId)
        }
    }

    override fun onPause() {
        // 取消广播注册
        unregisterReceiver(scanReceiver)
        super.onPause()
    }

    // 修改扫描工具参数：广播名、条码发送方式、声音、震动等
    private fun boardCastSetting() {
        val intent = Intent("com.android.scanner.service_settings")
        //修改广播名称：修改扫描工具广播名，接收广播时也是这个广播名
        intent.putExtra("action_barcode_broadcast", SCAN_ACTION)
        //条码发送方式：广播；其他设置看文档
        intent.putExtra("barcode_send_mode", "BROADCAST")
        //键值，一般不改
        intent.putExtra("key_barcode_broadcast", "scannerdata")
        //声音
        intent.putExtra("sound_play", true)
        //震动
        intent.putExtra("viberate", true)
        //其他参数设置参照：Android扫描服务设置.doc
        sendBroadcast(intent)
    }
}